<template>
  <div class="graduation-management">
    <!-- 学生视图 -->
    <div v-if="role === 'STUDENT'">
      <el-card v-if="!graduationApplication || graduationApplication.status === 'REJECTED'">
        <template #header>
          <div class="card-header">
            <span>毕业申请</span>
          </div>
        </template>
        <div v-if="graduationApplication && graduationApplication.status === 'REJECTED'" class="reject-reason">
          <el-alert
            title="您的上一次申请被拒绝"
            type="error"
            :description="graduationApplication.rejectReason"
            show-icon
          />
        </div>
        <el-button type="primary" @click="applyForGraduation">申请毕业</el-button>
      </el-card>

      <el-card v-else>
        <template #header>
          <div class="card-header">
            <span>毕业申请状态</span>
          </div>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="申请日期">
            {{ formatDate(graduationApplication.applicationDate) }}
          </el-descriptions-item>
          <el-descriptions-item label="申请状态">
            <el-tag :type="getStatusType(graduationApplication.status)">
              {{ getStatusText(graduationApplication.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学分是否充足">
            <el-tag :type="graduationApplication.isCreditSufficient ? 'success' : 'danger'">
              {{ graduationApplication.isCreditSufficient ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学业预警是否解决">
            <el-tag :type="graduationApplication.isWarningResolved ? 'success' : 'danger'">
              {{ graduationApplication.isWarningResolved ? '是' : '否' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item v-if="graduationApplication.reviewDate" label="审核日期">
            {{ formatDate(graduationApplication.reviewDate) }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
    </div>
    
    <!-- 管理员视图 -->
    <div v-else-if="role === 'ADMIN'">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>毕业申请管理</span>
            <div class="header-controls">
              <el-input
                v-model="searchQuery"
                placeholder="搜索学生姓名/学号"
                style="width: 250px; margin-right: 10px"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><search /></el-icon>
                </template>
              </el-input>
              <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px" @change="handleSearch">
                <el-option label="全部" value=""></el-option>
                <el-option label="审核中" value="PENDING"></el-option>
                <el-option label="已批准" value="APPROVED"></el-option>
                <el-option label="已拒绝" value="REJECTED"></el-option>
              </el-select>
              <el-button type="primary" size="small" @click="fetchGraduationApplications" style="margin-left: 10px;">刷新</el-button>
            </div>
          </div>
        </template>
        
        <el-empty v-if="applications.length === 0" description="暂无毕业申请" />
        
        <el-table v-else :data="filteredApplications" style="width: 100%">
          <el-table-column prop="studentName" label="学生姓名" width="120" />
          <el-table-column prop="studentNumber" label="学号" width="120" />
          <el-table-column prop="applicationDate" label="申请日期" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.applicationDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isCreditSufficient" label="学分是否充足" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.isCreditSufficient ? 'success' : 'danger'">
                {{ scope.row.isCreditSufficient ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isWarningResolved" label="预警是否解决" width="120">
            <template #default="scope">
              <el-tag :type="scope.row.isWarningResolved ? 'success' : 'danger'">
                {{ scope.row.isWarningResolved ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <div v-if="scope.row.status === 'PENDING'">
                <el-button 
                  type="success" 
                  size="small" 
                  @click="approveGraduation(String(scope.row.id))"
                >
                  批准
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="showRejectDialog(String(scope.row.id), scope.row.isCreditSufficient)"
                >
                  拒绝
                </el-button>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            v-if="applications.length > 0"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredApplications.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-card>
      
      <!-- 拒绝毕业申请对话框（其他原因） -->
      <el-dialog v-model="rejectDialogVisible" title="拒绝毕业申请" width="500px">
        <el-form :model="rejectForm">
          <el-form-item label="拒绝原因" label-width="100px">
            <el-input 
              v-model="rejectForm.reason" 
              type="textarea" 
              :rows="4"
              placeholder="请输入拒绝原因"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="rejectDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="rejectGraduation(rejectForm.applicationId, rejectForm.reason)">
              确认拒绝
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 拒绝毕业申请对话框（学分不足） -->
      <el-dialog v-model="creditRejectDialogVisible" title="拒绝毕业申请（学分不足）" width="600px">
        <el-form :model="creditRejectForm">
          <el-form-item label="专业要求学分" label-width="150px">
            <el-input-number v-model="creditRejectForm.requiredCredits" :min="0" :precision="1"></el-input-number>
          </el-form-item>
          <el-form-item label="已修学分" label-width="150px">
            <el-input-number v-model="creditRejectForm.currentCredits" :min="0" :precision="1" disabled></el-input-number>
          </el-form-item>
          <el-form-item label="需要补修学分" label-width="150px">
            <el-input-number v-model="creditRejectForm.missingCredits" :min="0" :precision="1" disabled></el-input-number>
          </el-form-item>
          <el-form-item label="建议补修" label-width="150px">
            <el-input 
              v-model="creditRejectForm.suggestion" 
              type="textarea" 
              :rows="3"
              placeholder="请输入建议补修的课程或方向"
            ></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="creditRejectDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="rejectGraduationWithCreditInfo(creditRejectForm.applicationId)">
              确认拒绝
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'GraduationManagement',
  components: {
    Search
  },
  props: {
    studentId: {
      type: [Number, String],
      required: true
    },
    role: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const graduationApplication = ref(null)
    const applications = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const searchQuery = ref('')
    const statusFilter = ref('')
    
    // 拒绝对话框（其他原因）
    const rejectDialogVisible = ref(false)
    const rejectForm = ref({
      applicationId: null,
      reason: ''
    })
    
    // 拒绝对话框（学分不足）
    const creditRejectDialogVisible = ref(false)
    const creditRejectForm = ref({
      applicationId: null,
      requiredCredits: 120.0,
      currentCredits: 0.0,
      missingCredits: 0.0,
      suggestion: ''
    })
    
    // 监听必修学分变化，自动计算差额
    watch(() => creditRejectForm.value.requiredCredits, (newVal) => {
      creditRejectForm.value.missingCredits = Math.max(0, newVal - creditRejectForm.value.currentCredits).toFixed(1);
    })
    
    // 过滤后的申请列表
    const filteredApplications = computed(() => {
      let filtered = [...applications.value]
      
      // 状态筛选
      if (statusFilter.value) {
        filtered = filtered.filter(item => 
          item.status === statusFilter.value
        )
      }
      
      // 搜索筛选
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(item => 
          (item.studentNumber && item.studentNumber.toString().toLowerCase().includes(query)) ||
          (item.studentName && item.studentName.toLowerCase().includes(query))
        )
      }
      
      return filtered
    })

    const fetchGraduationStatus = async () => {
      if (!props.studentId) {
        ElMessage.warning('未获取到学生ID')
        return
      }

      try {
        const response = await axios.get(`/api/users/me/graduation/status`, {
          params: {
            studentId: props.studentId
          }
        })
        graduationApplication.value = response.data
      } catch (error) {
        console.error('获取毕业申请状态失败:', error)
        if (error.response && error.response.status === 403) {
          ElMessage.error('没有权限访问毕业申请状态')
        } else {
          ElMessage.error('获取毕业申请状态失败')
        }
      }
    }
    
    // 获取所有毕业申请
    const fetchGraduationApplications = async () => {
      try {
        const response = await axios.get('/api/admin/graduations', {
          params: {
            page: currentPage.value,
            size: pageSize.value
          }
        })
        applications.value = response.data.map(app => ({
          ...app,
          id: String(app.id),
          studentNumber: String(app.studentNumber),
          reviewerId: app.reviewerId == null ? null : String(app.reviewerId)
        }))
      } catch (error) {
        console.error('获取毕业申请列表失败:', error)
        ElMessage.error('获取毕业申请列表失败')
      }
    }

    const applyForGraduation = async () => {
      try {
        await ElMessageBox.confirm(
          '提交毕业申请后，系统将自动检查您的学业预警情况。确定要申请毕业吗？',
          '确认申请',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const application = {
          studentId: props.studentId,
          applicationDate: new Date().toISOString(),
          status: 'PENDING'
        }

        const response = await axios.post('/api/users/me/graduation/apply', application)
        if (typeof response.data === 'string' && response.data.includes('学业预警')) {
          ElMessage.error(response.data)
        } else {
          ElMessage.success(response.data)
          fetchGraduationStatus()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('提交毕业申请失败:', error)
          ElMessage.error('提交毕业申请失败')
        }
      }
    }
    
    // 批准毕业申请
    const approveGraduation = async (id) => {
      const applicationId = String(id)
      try {
        await ElMessageBox.confirm('确认批准该学生的毕业申请？', '确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'info'
        })
        const response = await axios.put(`/api/admin/graduations/${applicationId}/approve`)
        if (typeof response.data === 'string' && response.data.includes('学分不足')) {
          // 学分不足，弹出学分不足拒绝对话框
          const application = applications.value.find(app => String(app.id) === applicationId)
          if (application) {
            creditRejectForm.value.applicationId = applicationId
            creditRejectForm.value.requiredCredits = 120.0
            // 获取学生的学分统计
            axios.get(`/api/users/me/grade-statistics`, {
              params: {
                studentId: application.studentId
              }
            })
              .then(res => {
                const stats = res.data
                creditRejectForm.value.currentCredits = parseFloat(stats.totalCredits || 0)
                creditRejectForm.value.missingCredits = Math.max(0, creditRejectForm.value.requiredCredits - creditRejectForm.value.currentCredits)
                creditRejectForm.value.suggestion = '建议补修以下课程：'
                creditRejectDialogVisible.value = true
              })
              .catch(() => {
                creditRejectForm.value.currentCredits = 0.0
                creditRejectForm.value.missingCredits = creditRejectForm.value.requiredCredits
                creditRejectForm.value.suggestion = '建议补修以下课程：'
                creditRejectDialogVisible.value = true
              })
          }
        } else {
          ElMessage.success(response.data)
          fetchGraduationApplications()
          
          // 触发待办事项检查
          try {
            await axios.get('/api/admin/todo')
            window.dispatchEvent(new CustomEvent('check-admin-todos'))
          } catch (error) {
            console.error('更新待办事项状态失败:', error)
          }
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批准毕业申请失败:', error)
          ElMessage.error('批准毕业申请失败')
        }
      }
    }
    
    // 显示拒绝对话框
    const showRejectDialog = (applicationId, isCreditSufficient) => {
      const appId = String(applicationId)
      if (!isCreditSufficient) {
        const application = applications.value.find(app => String(app.id) === appId);
        if (application) {
          creditRejectForm.value.applicationId = appId;
          creditRejectForm.value.requiredCredits = 120.0; // 默认要求学分
          
          // 获取学生的学分统计
          axios.get(`/api/users/me/grade-statistics`, {
            params: {
              studentId: application.studentId
            }
          })
            .then(response => {
              console.log('获取学生学分统计成功:', response.data);
              const stats = response.data;
              creditRejectForm.value.currentCredits = parseFloat(stats.totalCredits || 0);
              creditRejectForm.value.missingCredits = Math.max(0, creditRejectForm.value.requiredCredits - creditRejectForm.value.currentCredits);
              creditRejectForm.value.suggestion = '建议补修以下课程：';
              creditRejectDialogVisible.value = true;
            })
            .catch(error => {
              console.error('获取学生学分统计失败:', error);
              if (error.response) {
                console.error('错误响应状态:', error.response.status);
                console.error('错误响应数据:', error.response.data);
              }
              ElMessage.error('获取学生学分统计失败');
              
              // 如果获取失败，使用默认值
              creditRejectForm.value.currentCredits = 0.0;
              creditRejectForm.value.missingCredits = creditRejectForm.value.requiredCredits;
              creditRejectForm.value.suggestion = '建议补修以下课程：';
              creditRejectDialogVisible.value = true;
            });
        }
      } else {
        rejectForm.value.applicationId = appId;
        rejectForm.value.reason = '';
        rejectDialogVisible.value = true;
      }
    }
    
    // 拒绝毕业申请（普通原因）
    const rejectGraduation = async (id, reason) => {
      const applicationId = String(id)
      try {
        if (!reason) {
          ElMessage.warning('请填写拒绝原因')
          return
        }
        const response = await axios.put(`/api/admin/graduations/${applicationId}/reject`, reason)
        ElMessage.success(response.data)
        rejectDialogVisible.value = false
        fetchGraduationApplications()
        
        // 触发待办事项检查
        try {
          await axios.get('/api/admin/todo')
          window.dispatchEvent(new CustomEvent('check-admin-todos'))
        } catch (error) {
          console.error('更新待办事项状态失败:', error)
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    // 拒绝毕业申请（学分不足）
    const rejectGraduationWithCreditInfo = async (id) => {
      const applicationId = String(id)
      try {
        if (!creditRejectForm.value.suggestion) {
          ElMessage.warning('请填写建议补修内容')
          return
        }
        const response = await axios.put(`/api/admin/graduations/${applicationId}/reject-credits`, creditRejectForm.value)
        ElMessage.success(response.data)
        creditRejectDialogVisible.value = false
        fetchGraduationApplications()
        
        // 触发待办事项检查
        try {
          await axios.get('/api/admin/todo')
          window.dispatchEvent(new CustomEvent('check-admin-todos'))
        } catch (error) {
          console.error('更新待办事项状态失败:', error)
        }
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    // 搜索处理
    const handleSearch = () => {
      // 使用计算属性自动过滤
    }
    
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    }

    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '审核中',
        'APPROVED': '已批准',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || '未知'
    }

    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const d = new Date(dateStr);
      return `${d.getFullYear()}/${d.getMonth()+1}/${d.getDate()} ${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`;
    }

    let timer = null
    onMounted(() => {
      if (props.role === 'STUDENT') {
        fetchGraduationStatus()
      } else if (props.role === 'ADMIN') {
        fetchGraduationApplications()
      }
      // 只定时调用 fetchGraduationApplications
      timer = setInterval(() => {
        fetchGraduationApplications()
      }, 5000)
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })

    return {
      graduationApplication,
      applications,
      filteredApplications,
      currentPage,
      pageSize,
      searchQuery,
      statusFilter,
      rejectDialogVisible,
      rejectForm,
      creditRejectDialogVisible,
      creditRejectForm,
      applyForGraduation,
      fetchGraduationStatus,
      fetchGraduationApplications,
      approveGraduation,
      showRejectDialog,
      rejectGraduation,
      rejectGraduationWithCreditInfo,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      getStatusType,
      getStatusText,
      formatDate
    }
  }
}
</script>

<style scoped>
.graduation-management {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  align-items: center;
}

.reject-reason {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>